<template>
  <view class="viewport">
    <!-- 导航栏 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <navigator open-type="navigateBack" class="back icon-left" hover-class="none"></navigator>
      <view class="title">个人信息</view>
    </view>
    <!-- 头像 -->
    <view class="avatar">
      <view @tap="onAvatarChange" class="avatar-content">
        <image class="image" :src="userInfo.avatar" mode="aspectFill" />
        <text class="text">点击修改头像</text>
      </view>
    </view>
    <!-- 表单 -->
    <view class="form">
      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">昵称</text>
          <input class="input" type="text" placeholder="请填写昵称" v-model="userInfo.nickname" />
        </view>
        <view class="form-item">
          <text class="label">手机号</text>
          <input class="input" type="text" placeholder="请填写手机号" v-model="userInfo.phone" />
        </view>
        <view class="form-item">
          <text class="label">性别</text>
          <radio-group @change="handleGenderChange">
            <label class="radio">
              <radio value="男" color="#27ba9b" :checked="userInfo?.gender == 1" />
              男
            </label>
            <label class="radio">
              <radio value="女" color="#27ba9b" :checked="userInfo?.gender == 2" />
              女
            </label>
            <label class="radio">
              <radio value="未知" color="#27ba9b" :checked="userInfo?.gender == 0" />
              未知
            </label>
          </radio-group>
        </view>
        <view class="form-item">
          <text class="label">生日</text>
          <picker class="picker" mode="date" start="1900-01-01" :end="new Date()" :value="userInfo?.birthday"
            @change="handleBirthdayChange">
            <view v-if="userInfo?.birthday">{{ userInfo?.birthday }}</view>
            <view class="placeholder" v-else>请选择日期</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">城市</text>
          <picker class="picker" mode="region" :value="['云南省', '昆明市', '呈贡区']" @change="handleRegionChange">
            <view v-if="userInfo?.region">{{ userInfo?.region }}</view>
            <view class="placeholder" v-else>请选择城市</view>
          </picker>
        </view>
      </view>
      <!-- 提交按钮 -->
      <button class="form-button" @tap="submitUserInfo">保 存</button>
    </view>
  </view>
</template>


<script setup>
import { getUserInfoAPI } from '@/services/user'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { updateUserInfoAPI } from '@/services/user'
import { userStore } from '@/stores/UserStore'
const memberStore = userStore()
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const userInfo = ref({
  id: null,
  phone: '',
  gender: null,
  nickname: '',
  avatar: '',
  birthday: '',
  region: '',
  totalPoints: null,
})
// 修改头像
const onAvatarChange = () => {
  //调用拍照或选择图片的API
  uni.chooseMedia({
    // 最多选择1张图片
    count: 1,
    // 只选择图片
    mediaType: ['image'],
    success: (res) => {
      const file = res.tempFiles[0]
      uni.uploadFile({
        url: '/uploadFile',
        filePath: file.tempFilePath,
        name: 'file',
        formData: {
          path: 'userAvatar', // 添加额外参数 path
        },
        success: (uploadRes) => {
          if (uploadRes.statusCode === 200) {
            const result = JSON.parse(uploadRes.data)
            userInfo.value.avatar = result.data
          }

        },
        fail: (error) => {
          console.log(error)
        }
      })
    },
    fail: (error) => {
      console.log(error)
    }
  })
}
// 获取用户信息
const getUserInfo = async () => {
  const result = await getUserInfoAPI()
  userInfo.value = result.data
  if (userInfo.value.birthday) {
    // 将 ISO 格式日期转换为 YYYY-MM-DD 格式
    const date = new Date(userInfo.value.birthday)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    userInfo.value.birthday = `${year}-${month}-${day}`
  }
  console.log(result)
}
onLoad(() => {
  getUserInfo()
})

const handleBirthdayChange = (e) => {
  const date = new Date(e.detail.value);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  userInfo.value.birthday = `${year}-${month}-${day}`;
};
const handleRegionChange = (e) => {
  const region = e.detail.value;
  userInfo.value.region = region.join(' ');
};

const handleGenderChange = (e) => {
  const value = e.detail.value;
  let genderValue = 0;

  if (value === '男') {
    genderValue = 1;
  } else if (value === '女') {
    genderValue = 2;
  } else {
    genderValue = 0;
  }

  userInfo.value.gender = genderValue;
};
const submitUserInfo = async () => {
  if (validateUserInfo()) {
    // 提交到后端 
    // 这里可以调用 API 提交数据
    const result = await updateUserInfoAPI(userInfo.value)
    if (result.code === 1) {
      setTimeout(() => {
        uni.showToast({ title: '提交成功', icon: 'success' });
      }, 200)
      //更新本地用户信息
      memberStore.updateUser(userInfo.value)
    } else {
      uni.showToast({ title: '提交失败', icon: 'error' });
    }

  }
};
const validateUserInfo = () => {
  const { nickname, phone, gender, birthday, region } = userInfo.value;

  // 昵称校验
  if (!nickname || nickname.trim().length < 2 || nickname.trim().length > 20) {
    uni.showToast({ title: '昵称不能为空且长度在2-20之间', icon: 'none' });
    return false;
  }

  // 手机号校验
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phone || !phoneReg.test(phone)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    return false;
  }

  // 性别校验
  if (gender === null || ![0, 1, 2].includes(gender)) {
    uni.showToast({ title: '请选择性别', icon: 'none' });
    return false;
  }

  // 生日校验
  if (!birthday) {
    uni.showToast({ title: '请选择生日', icon: 'none' });
    return false;
  }

  // 城市校验
  if (!region) {
    uni.showToast({ title: '请选择城市', icon: 'none' });
    return false;
  }

  return true;
};
</script>


<style lang="scss">
page {
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 头像
.avatar {
  text-align: center;
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 80rpx;
    min-height: 80rpx;
    padding: 20rpx 10rpx;
    align-items: center; // 垂直居中
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
      margin-bottom: 0;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
  }
}
</style>